package com.example.himalaya.model.dao;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.example.himalaya.base.BaseApplication;
import com.example.himalaya.model.ILoveSongDao;
import com.example.himalaya.model.XimalayaDBHelper;
import com.example.himalaya.view.callback.ILoveSongDaoCallback;
import com.example.himalaya.constants.Constants;
import com.example.himalaya.utils.LogUtil;
import com.ximalaya.ting.android.opensdk.model.PlayableModel;
import com.ximalaya.ting.android.opensdk.model.album.Announcer;
import com.ximalaya.ting.android.opensdk.model.track.Track;

import java.util.ArrayList;
import java.util.List;

public class LoveSongDao implements ILoveSongDao {


    private static final String TAG = "LoveSongDao";
    // Constant
    private ILoveSongDaoCallback mILoveSongDaoCallbacks;
    private final Object mLock;
    private SQLiteOpenHelper mDbHelper;


    public LoveSongDao() {
        mDbHelper = new XimalayaDBHelper(BaseApplication.getAppContext());

        mLock = new Object();
    }

    @Override
    public void registerCallback(ILoveSongDaoCallback callback) {
        mILoveSongDaoCallbacks = callback;
    }


    @Override
    public void addLoveSong(Track track) {
        synchronized (mLock) {
            SQLiteDatabase db = null;

            boolean isSuccess = false;
            try {
                db = mDbHelper.getWritableDatabase();
                db.beginTransaction();

                // 先去删除以后再去添加
                db.delete(Constants.LOVE_SONG_TB_NAME, Constants.LOVE_SONG_TRACK_ID + "=?", new String[]{track.getDataId() + ""});


                ContentValues values = new ContentValues();

                values.put(Constants.LOVE_SONG_COVER_URL, track.getCoverUrlLarge());
                values.put(Constants.LOVE_SONG_TRACK_ID, track.getDataId());
                values.put(Constants.LOVE_SONG_TITLE, track.getTrackTitle());
                values.put(Constants.LOVE_SONG_PLAY_COUNT, track.getPlayCount());
                values.put(Constants.LOVE_SONG_DURATION, track.getDuration());
                values.put(Constants.LOVE_SONG_UPDATE_TIME, track.getUpdatedAt());
                values.put(Constants.TRACK_AUTHOR_NAME, track.getAnnouncer().getNickname());

                db.insert(Constants.LOVE_SONG_TB_NAME, null, values);

                db.setTransactionSuccessful();

                isSuccess = true;
            } catch (Exception e) {
                e.printStackTrace();
                isSuccess = false;
            } finally {
                if (db != null) {
                    db.endTransaction();
                    db.close();
                }

                // 通知出去
                if (mILoveSongDaoCallbacks != null) {
                    mILoveSongDaoCallbacks.onLoveSongAdd(isSuccess);
                }
            }
        }
    }

    @Override
    public void clearLoveSong() {
        synchronized (mLock) {

            SQLiteDatabase db = null;

            boolean isSuccess = false;
            try {
                db = mDbHelper.getWritableDatabase();
                db.beginTransaction();

                int delete = db.delete(Constants.LOVE_SONG_TB_NAME, null, null);

                LogUtil.d(TAG, "删除的个数 -->" + delete);

                db.setTransactionSuccessful();

                isSuccess = true;

            } catch (Exception e) {
                e.printStackTrace();
                isSuccess = false;
            } finally {
                if (db != null) {
                    db.endTransaction();
                    db.close();
                }
                // 通知出去
                if (mILoveSongDaoCallbacks != null) {
                    mILoveSongDaoCallbacks.onLoveSongClean(isSuccess);
                }
            }
        }
    }

    @Override
    public void delLoveSong(Track track) {
        synchronized (mLock) {
            SQLiteDatabase db = null;

            boolean isSuccess = false;
            try {
                db = mDbHelper.getWritableDatabase();
                db.beginTransaction();

                int delete = db.delete(Constants.LOVE_SONG_TB_NAME, Constants.LOVE_SONG_TRACK_ID + "=?", new String[]{track.getDataId() + ""});

                LogUtil.d(TAG, "删除的个数 -->" + delete);

                db.setTransactionSuccessful();

                isSuccess = true;

            } catch (Exception e) {
                e.printStackTrace();
                isSuccess = false;
            } finally {
                if (db != null) {
                    db.endTransaction();
                    db.close();

                }
                // 通知出去
                if (mILoveSongDaoCallbacks != null) {
                    mILoveSongDaoCallbacks.onLoveSongDel(isSuccess);
                }
            }
        }
    }

    @Override
    public void listLoveSongs() {
        synchronized (mLock) {

            List<Track> result = new ArrayList<>();

            SQLiteDatabase db = null;
            boolean isSuccess = false;

            try {
                db = mDbHelper.getReadableDatabase();
                db.beginTransaction();


                Cursor query = db.query(Constants.LOVE_SONG_TB_NAME, null, null, null, null, null, Constants.SUB_ID + " desc");

                // 封装数据
                while (query.moveToNext()) {
                    Track track = new Track();

                    // 设置封面
                    String coverUrl = query.getString(query.getColumnIndex(Constants.LOVE_SONG_COVER_URL));
                    track.setCoverUrlLarge(coverUrl);
                    track.setCoverUrlMiddle(coverUrl);
                    track.setCoverUrlSmall(coverUrl);

                    // 设置标题
                    String title = query.getString(query.getColumnIndex(Constants.LOVE_SONG_TITLE));
                    track.setTrackTitle(title);

                    // 设置描述
                    int duration = query.getInt(query.getColumnIndex(Constants.LOVE_SONG_DURATION));
                    track.setDuration(duration);

                    // 设置tracks数量
                    long udpateAt = query.getLong(query.getColumnIndex(Constants.LOVE_SONG_UPDATE_TIME));
                    track.setUpdatedAt(udpateAt);

                    // 设置播放数量
                    int playCount = query.getInt(query.getColumnIndex(Constants.LOVE_SONG_PLAY_COUNT));
                    track.setPlayCount(playCount);


                    // 设置作者名字
                    String authorName = query.getString(query.getColumnIndex(Constants.TRACK_AUTHOR_NAME));
                    Announcer announcer = new Announcer();
                    announcer.setNickname(authorName);
                    track.setAnnouncer(announcer);

                    // 设置专辑id
                    long trackId = query.getLong(query.getColumnIndex(Constants.LOVE_SONG_TRACK_ID));
                    track.setDataId(trackId);

                    track.setKind(PlayableModel.KIND_TRACK);

                    result.add(track);
                }


                query.close();
                db.setTransactionSuccessful();
                isSuccess = true;
            } catch (Exception e) {
                e.printStackTrace();
                // LogUtil.d(TAG, "数据库查询有错吗");
                isSuccess = false;
            } finally {
                if (db != null) {
                    db.endTransaction();
                    db.close();
                }


                if (isSuccess) {
                    // 通知出去
                    if (mILoveSongDaoCallbacks != null) {
                        mILoveSongDaoCallbacks.onLoveSongLoaded(result);
                    }
                }


            }
        }
    }
}

